#include "iConfig.hpp"

#if GLF_ENABLE_DEBUGGER

#include <glf/core/timer.h>
#include <glf/debugger/network.h>

namespace glf
{
namespace debugger
{
	Network::Network() :
		Module("NETWORK"),
		mEnabled(false)
	{
	}

	GLF_DEFINE_SINGLETON_WITH_DEP(Network, Debugger)

	Network::~Network()
	{
        if( glf::debugger::Debugger::GetInstance() )
        {
		    glf::debugger::Debugger::GetInstance()->UnregisterModule( this );
        }
	}

	void Network::AddEvent(const Event& event)
	{	
		ScopeMutex mutex;
		Network* netInst = GetInstance();
		if(netInst->mEnabled && Debugger::GetInstance()->IsConnected())
		{
			netInst->mPendingEvents.resize(netInst->mPendingEvents.size() + 1);
			
			PendingEvent& pe = netInst->mPendingEvents.back();
			pe.mType = event.mType;
			pe.mId = event.mId;
			pe.mText = event.mText;
			pe.mTimeStamp = GetMicroseconds();
			
			if(event.mDataSize > 0)
			{
				pe.mData.resize(event.mDataSize);
				memcpy(&pe.mData[0], event.mData, event.mDataSize);
			}
		}
	}

	void Network::UpdateFrame()
	{
		SendEvents();
	}

	void Network::Parse(int type, PacketReader& in)
	{
		switch(type)
		{
		case MESSAGE_SET_ENABLED:
			mEnabled = in.ReadIntLE() != 0;
			break;
		}
	}

	void Network::ConnectionClosed()
	{
		ScopeMutex mutex;
		mEnabled = false;
		
		mPendingEvents.clear();
	}

	void Network::SendEvents()
	{
		if(!Debugger::GetInstance()->IsConnected())
			return;

		ScopeMutex mutex;
		
		if(mPendingEvents.size() == 0)
			return;

		PacketWriter& pw = GetPacketWriter();
		pw.Init(MESSAGE_EVENTS);
		pw.Write((uint)mPendingEvents.size());

		for(uint i = 0; i < mPendingEvents.size(); i++)
		{
			PendingEvent& pe = mPendingEvents[i];
			pw.Write(pe.mType);
			pw.Write(pe.mId);
			pw.Write(pe.mText.c_str());
			pw.Write(pe.mTimeStamp);
			pw.Write((uint)pe.mData.size());
			
			if(pe.mData.size() > 0)
				pw.Write(&pe.mData[0], pe.mData.size());
		}
		
		Send(pw);
		mPendingEvents.clear();
	}

} //namespace debugger
} //namespace glf

#endif // GLF_ENABLE_DEBUGGER
